import os

from django.http import HttpResponse
from django.shortcuts import render
from pathlib import Path
from django.views.decorators.csrf import csrf_exempt
from urlsetting import *



@csrf_exempt
def hello(request):
    success = 0;
    if request.method == 'POST':
        file = request.FILES.get('file')
        name = request.POST.get('name')

        if name:
            sp = name.split("::")
            type = sp[1]
            name = sp[0]
            size = sp[2]
            name = name.replace('"',"_").replace(".","'").\
                replace("?","_").replace("/","_").\
                replace(" ","_")
            if type=='music':
                filepath = Path(MUSIC_PATH + name)
            if type=='pic':
                filepath = Path(PIC_PATH + name)
            if type=='video':
                filepath = Path(VIDEO_PATH + name)
            if filepath.exists():
                if int(os.path.getsize(filepath)) < int(size):
                    print('phone'+size)
                    print(os.path.getsize(filepath))
                    print(filepath)
                    os.remove(filepath)
                    while(filepath.exists()):
                        print('1111')
                    print('size is not same')
                    return HttpResponse('true')
                return HttpResponse('false')
            return HttpResponse('true')

        if file:
            type = file.name.split("::")[1]
            name = file.name.split("::")[0]
            name = name.replace('"',"_").replace(".","'").\
                replace("?","_").replace("/","_").\
                replace(" ","_")
            if type == 'music':
                filepath = Path(MUSIC_PATH + name)
            if type == 'pic':
                filepath = Path(PIC_PATH + name)
            if type == 'video':
                filepath = Path(VIDEO_PATH + name)
            destination = open(filepath,'wb+')
            for chunk in file.chunks():
                destination.write(chunk)
            destination.close()
            success+=1

        return render(request,'hello.html')
    return render(request,'hello.html')
